package handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import enums.MessageTypeEnum;
import exception.BizException;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.CharsetUtil;
import message.BinaryMessage;
import message.LoginMessage;
import message.Message;
import message.StringMessage;

import java.util.List;

/**
 * @author wb_zhulinzhong
 * @date 2021-04-14 16:54:47
 */
public class ComByteToMessageDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in == null) {
            return;
        }
        if (in.readableBytes() <= 4) {
            return;
        }

        in.markReaderIndex();
        int len = in.readInt();
        if (in.readableBytes() < len) {
            in.resetReaderIndex();
            return;
        }

        byte[] bytes = new byte[len];
        in.readBytes(bytes);

        String msg = new String(bytes, CharsetUtil.UTF_8);
        JSONObject messageJson = JSON.parseObject(msg);
        MessageTypeEnum type = MessageTypeEnum.getMessageTypeEnum(messageJson.getInteger("type"));

        switch (type){
            case TEXT:
                out.add(jsonToMessage(messageJson, new StringMessage()));
                return;
            case BINARY:
                out.add(jsonToMessage(messageJson, new BinaryMessage()));
                return;
            case LOGIN:
                LoginMessage loginMessage = new LoginMessage();
                loginMessage.setLogin(messageJson.getBoolean("login"));
                out.add(jsonToMessage(messageJson, loginMessage));
                return;
            default:
                throw new BizException("该消息类型暂未支持");
        }
    }

    private Message jsonToMessage(JSONObject messageJson, Message message){
        message.setUId(messageJson.getString("uId"));
        message.setToUId(messageJson.getString("toUId"));
        message.setByteDataEncode(messageJson.getString("byteDataEncode"));
        message.setType(messageJson.getInteger("type"));
        return message;
    }
}
